const scpClient = require('scp2')
const chalk = require('chalk')
const server = require('./deploy.config.js')
const path = require('path')
let source_path = path.resolve() + '/dist'
var Client = require('ssh2').Client
var conn = new Client()
var ora = require('ora')
//环境变量 =  console.log(process.env.VUE_APP_MY_NODE_ENV);   //TASK Production
const spinner = ora('正在发布到服务器...')
spinner.start()
conn
  .on('ready', function() {
    // rm 删除dist文件，\n 是换行 换行执行 重启nginx命令 我这里是用docker重启nginx
    conn.exec('rm -rf /www/wwwroot/test/xmgallery', function(err, stream) {
      if (err) throw err
      stream
        .on('close', function(code, signal) {
          // 在执行shell命令后，把开始上传部署项目代码放到这里面
          scpClient.scp(
            source_path,
            {
              host: server.host,
              port: server.port,
              username: server.username,
              password: server.password,
              path: server.path,
            },
            function(err) {
              spinner.stop()

              if (err) {
                console.log(chalk.red('发布失败.\n'))
                throw err
              } else {
                console.log(chalk.green('Success! 成功发布到服务器! \n'))
              }
            }
          )

          conn.end()
        })
        .on('data', function(data) {
          console.log('STDOUT: ' + data)
        })
        .stderr.on('data', function(data) {
          console.log('STDERR: ' + data)
        })
    })
  })
  .connect({
    host: server.host,
    port: server.port,
    username: server.username,
    password: server.password,
    //privateKey: require('fs').readFileSync('/home/admin/.ssh/id_dsa')
  })
